import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Query {

	private String query;
	private HashMap<String,String> params = new HashMap<String, String>();

	public Query(String query) throws MalformedURLException{
		this.query = new URL(query).getQuery();
		extractQueryParams();
	}
	
	private void extractQueryParams(){
		String[] params = query.split("&");
		String[] pair = null;
		for (String param : params){
			pair = param.split("=");
			if (pair.length ==2) { 
				String name = pair[0];
				String value =pair[1];
				this.params.put(name, value);
			}
			else if (pair.length == 1)
				this.params.put(pair[0], null);
		}
	}
	
	public void setValues(){
		Iterator it = params.entrySet().iterator();
		while (it.hasNext()){
			Map.Entry<String, String> pair = (Map.Entry<String, String>)it.next();
			//System.out.println("Parameter: " + pair.getKey());
			//System.out.println("Current value: " + pair.getValue());
			//TODO: get user input if he would like to change some values.
			// keep on getting user input and then need to convert all inputs to a URL array
		}
	}
	
	@Override
	public boolean equals(Object obj) {
		if (obj instanceof Query) {
			Query other = (Query) obj;
			return (this.params.equals(other.params));
		}
		return false;
	}
	public String toString() {
		StringWriter bw = new StringWriter();
		Iterator<String> iter = params.keySet().iterator();
		while (iter.hasNext()){
			String key = iter.next();
			bw.write("\t" + key);
			bw.write("=");
			if (params.get(key)!=null){
				bw.write(params.get(key));
			}	
			else 
				bw.write("\" \"");
			bw.write("\r\n");
		}
		return(bw.toString());
	}
	public HashMap<String, String> getParams() {
		return params;
	}

}
